<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小账单物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82882996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\approval;

use think\App;
use app\controller\property\Base;
use app\validate\approval\ApprovalConfigValidate;
use app\common\repositories\property\users\propertyUsersRepository;
use app\common\repositories\approval\ApprovalConfigRepository;

class ApprovalConfig extends Base
{

    protected $repository;

    public function __construct(App $app, ApprovalConfigRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'isTypeData' => $this->repository::IS_TYPE,
            'addAuth' => property_auth('propertyApprovalConfigAdd'),
            'editAuth' => property_auth('propertyApprovalConfigEdit'),
            'delAuth' => property_auth('propertyApprovalConfigDel'),
            'detailAuth' => property_auth('propertyApprovalConfigDetail'),
        ]);
    }

    /**
     * 流程参数列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-22 07:54
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'is_type' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }

        return $this->fetch('approval/config/list');
    }

    /**
     *  添加流程参数
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-22 07:55
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'typeData') {
            $isType = $this->request->param('isType');
            if ($isType == 1) {
                $classData = $this->repository::FLOW_TYPE_A;
            } elseif ($isType == 2) {
                $classData = $this->repository::FLOW_TYPE_B;
            } elseif ($isType == 3) {
                $classData = $this->repository::FLOW_TYPE_C;
            } else {
                $classData = [];
            }
            $typeIds = $this->repository->getSearch([])
                ->where('property_id', $this->request->propertyId)
                ->column('flow_type');
            foreach ($classData as $k => $v) {
                if (in_array($k, $typeIds)) {
                    unset($classData[$k]);
                }
            }
            return json()->data(['code' => 0, 'data' => $classData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'is_type' => '',
                'audit_type' => '',
                'flow_type' => '',
                'accept_uids' => '',
                'copy_uids' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            $flowTypeData = array_merge($this->repository::FLOW_TYPE_A, $this->repository::FLOW_TYPE_B, $this->repository::FLOW_TYPE_C);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'flow_type', $param['flow_type'])) {
                return $this->error(($flowTypeData['flow_type'] ?? '') . ' 流程已存在');
            }
            validate(ApprovalConfigValidate::class)->scene('add')->check($param);
            $param['accept_uids'] = str_replace(['[', ']'], '', $param['accept_uids']);
            $param['copy_uids'] = str_replace(['[', ']'], '', $param['copy_uids']);
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加流程参数失败', $e);
                return $this->error('网络失败');
            }
        } else {
            /** @var PropertyUsersRepository $propertyUsersRepository */
            $propertyUsersRepository = app()->make(PropertyUsersRepository::class);
            $propertyUsersData = $propertyUsersRepository->getCascaderData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('approval/config/add', [
                'propertyUsersData' => $propertyUsersData
            ]);
        }
    }

    /**
     *  编辑流程参数
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-22 07:55
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'accept_uids' => '',
                'copy_uids' => '',
                'audit_type' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            $param['is_type'] = $info['is_type'];
            validate(ApprovalConfigValidate::class)->scene('edit')->check($param);
            $param['accept_uids'] = str_replace(['[', ']'], '', $param['accept_uids']);
            $param['copy_uids'] = str_replace(['[', ']'], '', $param['copy_uids']);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑流程参数失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var PropertyUsersRepository $propertyUsersRepository */
            $propertyUsersRepository = app()->make(PropertyUsersRepository::class);
            $propertyUsersData = $propertyUsersRepository->getCascaderData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('approval/config/edit', [
                'info' => $info,
                'propertyUsersData' => $propertyUsersData
            ]);
        }
    }

    /**
     * 流程参数详情
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-05-22 07:55
     */
    public function detail()
    {
        $id = (int)$this->request->param('id');
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('approval/config/detail', [
            'info' => $info,
        ]);
    }

    /**
     * 删除流程参数
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-05-22 07:55
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除流程参数失败', $e);
            return $this->error('网络失败');
        }
    }
}